import wxValidate from 'wechat-validate'
const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile: '15660762022',
    code: '',
    redirectRoute: ''
  },
  onLoad (ev) {
    console.log(ev)
    this.setData({ redirectRoute: ev.route })
  },
  behaviors: [wxValidate],
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' }
    ]
  },
  code: {
    code: [
      { required: true, message: '请填写验证码!' },
      { pattern: /^\d{6}$/, message: '请填写正确的验证码!' }
    ]
  },
  countDownChange (ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0
    })
  },
  async showCountDown () {
    const { message, valid } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    this.setData({
      countDownVisible: true
    })
    const res = await wx.http.get('/code', { mobile: this.data.mobile })
    console.log(res.data)
  },
  async getSMSCode () {
    const { message, valid } = this.validate('code')
    if (!valid) return wx.utils.toast(message)
    const res = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code
    })
    console.log(res.data)
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    // wx.redirectTo
    wx.redirectTo({
      url: '/' + this.data.redirectRoute
    })
  }
})
